package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth.ChangePasswordBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth.RoleInfoFunctionBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth.RoleInfoFunctionWebBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth.UserBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PersonalExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.UserVo;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 用户管理控制器
 *
 * @author xiaoxu
 * @version 1.0
 * @date 2022/12/25 15:00
 * @since 1.0
 */
@CrossOrigin()
@RestController
@RequestMapping(value = "/personal")
public class PersonalController {
    @Autowired
    private ChangePasswordBu changePasswordBu;
    @Autowired
    private RoleInfoFunctionBu roleInfoFunctionBu;
    @Autowired
    private UserBu userBu;
    @Autowired
    private RoleInfoFunctionWebBu roleInfoFunctionWebBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;
//    修改密码

    /**
     * 修改密码
     *
     * @param jsonParam：旧密码和新密码{oldPassword:xxx,newPassword:xxx}
     * @param request：请求
     */
    @PostMapping("/changePassword")
    public SzResult changePassword(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String oldPassword = jsonParam.getString("oldPassword");
        String newPassword = jsonParam.getString("newPassword");

//        Map userPermissionWeb = userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString());
//        Map permission = webFunctionUtil.webFunction(userPermissionWeb, "user_changePassword");
//        if (   permission.get("code").equals(0)) {
//            return SzResult.error(permission.get("msg").toString());
//        }
        return changePasswordBu.changePassword(token, oldPassword, newPassword);
    }


    @GetMapping("/getUserRoleInfoFunction")
    public SzResult RoleInfoFunction(@RequestParam(value = "id", required = false) String id,
                                     HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        return SzResult.success(roleInfoFunctionBu.getUserFunction(id));
    }
//    用户手机权限修改

    /**
     * 用户权限修改
     *
     * @param jsonParam：用户id和权限id{userId:xxx,roleId:xxx}
     * @param request：请求
     */
    @PostMapping("/updateUserRoleInfoFunction")
    @PermissionCheck("user_updateUserRoleInfoFunction")
    public SzResult changeRoleFunction(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String userId = jsonParam.getString("id");
        String functionNum = jsonParam.getString("functionNum");
        String state = jsonParam.getString("state");
        String plantId = request.getHeader("Plant-Id");
        return roleInfoFunctionBu.updateUserFunction(token, userId, functionNum, state,plantId);
    }
//    用户网页端权限修改

    /**
     * 用户权限修改
     *
     * @param jsonParam：用户id和权限id{userId:xxx,roleId:xxx}
     * @param request：请求
     */
    @PostMapping("/updateUserRoleInfoFunctionWeb")
    @PermissionCheck("user_updateUserRoleInfoFunctionWeb")
    public SzResult changeRoleFunctionWeb(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String userId = jsonParam.getString("id");
        String functionNum = jsonParam.getString("functionNum");
        String state = jsonParam.getString("state");
        String plantId = request.getHeader("Plant-Id");
        return roleInfoFunctionWebBu.updateUserFunction(token, userId, functionNum, state,plantId);
    }
//    新增用户

    /**
     * 新增用户
     *
     * @param jsonParam：用户id和权限id{userId:xxx,roleId:xxx}
     * @param request：请求
     */
    @PostMapping("/addUser")
    @PermissionCheck("user_add")
    public SzResult addUserRoleInfoFunction(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        UserVo userVo = jsonParam.toJavaObject(UserVo.class);
        return userBu.addUser(token, userVo,plantId);
    }
//    修改用户

    /**
     * 修改用户
     *
     * @param jsonParam：用户id和权限id{userId:xxx,roleId:xxx}
     * @param request：请求
     */
    @PostMapping("/updateUser")
    @PermissionCheck("user_update")
    public SzResult updateUserRoleInfoFunction(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//       传过来的数据是实体类UserVo
        UserVo userVo = jsonParam.toJavaObject(UserVo.class);
        List<String> plantList = jsonParam.getObject("plantList", List.class);
        return userBu.updateUser(token, userVo,plantList,plantId);
    }
//    删除用户

    /**
     * 删除用户
     *
     * @param jsonParam：用户id和权限id{userId:xxx,roleId:xxx}
     * @param request：请求
     */
    @PostMapping("/deleteUser")
    @PermissionCheck("user_delete")
    public SzResult deleteUserRoleInfoFunction(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//       传过来的数据是实体类UserVo
        String id = jsonParam.getString("id");
        return userBu.deleteUser(token, id,plantId);
    }

    /**
     * 获取用户列表
     *
     * @param page：页码    pageSize：每页条数
     *                   userName：用户名
     *                   phone：手机号
     * @param request：请求
     */
    @GetMapping("/getAllUser")
    public SzResult getAllUser(@RequestParam(value = "userName", required = false) String userName,
                               @RequestParam(value = "phone", required = false) String phone,
                               @RequestParam(value = "coId", required = false) String coId,
                               @RequestParam(value = "page", required = false) String page,
                               @RequestParam(value = "pageSize", required = false) String pageSize,
                               @RequestParam(value = "roleId", required = false) String roleId
            , HttpServletRequest request) throws Exception {
        String plantId = request.getHeader("Plant-Id");
        return userBu.getAllUser(page, pageSize, userName, phone,coId, roleId, plantId);
    }
//获取系统的管理层及以上的用户
    @GetMapping("/getSystemUser")
    public SzResult getSystemUser(
            @RequestParam(value = "value", required = false) String value,
            HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.getSystemUser(value,token,plantId);
    }
    /**
     * 重置用户密码
     *
     * @param jsonParam：用户id roleLevel：用户角色
     * @param request：请求
     */
    @PostMapping("/resetPassword")
    @PermissionCheck("user_resetPassword")
    public SzResult resetPassword(@RequestBody JSONObject jsonParam, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String id = jsonParam.getString("id");
        String plantId = request.getHeader("Plant-Id");
        return userBu.resetUserPwd(token, id,plantId);
    }

    //    更新用户权限APP_AUTHORITY
    @PostMapping("/updateAppAuthority1")
    @PermissionCheck("part_updateDefaultCodeApp")
    public SzResult updateAppAuthority1(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        //将请求体中的list集合拿出来
        Integer number = jsonObject.getInteger("number");
        Integer ifOn = jsonObject.getInteger("ifOn");
        String id = jsonObject.getString("id");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.updateAppAuthority1(number, id, ifOn, token,plantId);
    }

    @PostMapping("/updateAppAuthority2")
    @PermissionCheck("part_updateDefaultCodeWeb")
    public SzResult updateAppAuthority2(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        //将请求体中的list集合拿出来
        String number1 = jsonObject.getString("number");
        Integer number = Integer.parseInt(number1);
        Integer ifOn = jsonObject.getInteger("ifOn");
        String id = jsonObject.getString("id");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.updateAppAuthority2(number, id, ifOn, token,plantId);
    }
    //一键重置了不同角色用户权限
    @PostMapping("/resetAllAuthority")
    public SzResult resetAllAuthority(@RequestBody JSONObject jsonObject ,HttpServletRequest request) throws Exception {
        String partId = jsonObject.getString("partId");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.resetAllAuthority(partId,token,plantId);
    }
    //重置用户权限
    @PostMapping("/resetAuthority")
    public SzResult resetAuthority(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String id = jsonObject.getString("id");
        return userBu.resetAuthority(id,token,plantId);
    }
    /**
     * 用戶导出excel
     *
     * @param jsonParam
     * @param response
     * @param request
     * @throws Exception
     */
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
        String filename = jsonParam.getString("filename");
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
        boolean isHeader = jsonParam.getBoolean("isHeader");
        String mode = jsonParam.getString("mode");
        Boolean original = jsonParam.getBoolean("original");
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
        String sheetName = jsonParam.getString("sheetName");
        Map<String, String> form = jsonParam.getObject("form", Map.class);
        String trueName = null;
        String phone = null;
        if (form.get("trueName") != null && !form.get("trueName").equals("null")) {
            trueName = form.get("trueName").toString();
        }
        if (form.get("phone") != null && !form.get("phone").equals("null")) {
            phone = form.get("phone").toString();
        }
        Future<List<PersonalExcelEn>> listFuture = userBu.userExportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, plantId, trueName, phone);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<PersonalExcelEn> personalExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), PersonalExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("用户")
                .doWrite(personalExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    /**
     * 获取司机用户
     */
    @GetMapping("/getDriverUser")
    public SzResult getDriverUser(@RequestParam(required = false) String driver,HttpServletRequest request) throws Exception {
        String plantId = request.getHeader("Plant-Id");
        return userBu.getDriver(driver,plantId);
    }
    /**
     * 冻结用户
     */
    @GetMapping("/frozenUser")
    public SzResult frozenUser(@RequestParam(required = false) String id,HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.frozenUser(id,token,plantId);
    }

    /**
     * 解冻
     */
    @GetMapping("/unfrozenUser")
    public SzResult unfrozenUser(@RequestParam(required = false) String id,HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return userBu.unfrozenUser(id,token,plantId);
    }

    /**
     * 修改用户关联厂
     */
    @PostMapping("/updateUserConnectPlant")
    public SzResult updateUserConnectPlant(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
//        if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("part_updateDefaultCode")) {
//            return SzResult.error("您没有修改部门默认权限码App的权限");
//        }
//        if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(request.getHeader("Authorization")).toString()).containsKey("updateUserConnectPlant")) {
//            return SzResult.error("您没有修改用户关联厂权限");
//        }
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String id = jsonObject.getString("id");
        List<String> plantIdList = jsonObject.getObject("plantIdList", List.class);
        return userBu.updateUserConnectPlant(id,plantIdList,token,plantId);
    }

    /**
     * 修改用户关联微信id
     */
    @PostMapping("/updateUserWxConn")
    public SzResult updateUserWxConn(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String id = jsonObject.getString("id");
        String wxOpenId = jsonObject.getString("wxOpenId");
        return userBu.updateUserWxConn(id,wxOpenId,token);
    }
}
